package com.vvvtimes.demo.util.endecrypt;

import cn.hutool.core.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

public class BcRsaUtil {
    private static final BouncyCastleProvider provider;




    private static PrivateKey getPrivateKey(String pkcs8Key) {

        byte[] pkcs8Keybytes = Base64.decode(pkcs8Key.getBytes(Charset.forName("UTF-8")));
        final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(pkcs8Keybytes);
        try {
            return KeyFactory.getInstance("RSA", provider).generatePrivate(pkcs8EncodedKeySpec);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * RSA私钥解密
     *
     * @param inputByte 待解密字节数组
     * @param pkcs8Key  私钥
     * @return 明文
     */
    public static byte[] decrypt(byte[] inputByte, String pkcs8Key) {
        byte[] outputeByte = null;
        try {
            PrivateKey privateKey = getPrivateKey(pkcs8Key);
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA", provider);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            outputeByte = cipher.doFinal(inputByte);

        } catch (NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return outputeByte;
    }

    public static byte[] sign(final byte[] array, String pkcs8Key) {
        try {
            PrivateKey privateKey = getPrivateKey(pkcs8Key);
            final Signature instance = Signature.getInstance("SHA1withRSA", provider);
            instance.initSign(privateKey);
            instance.update(array);
            return instance.sign();
        } catch (GeneralSecurityException ex) {
            throw new RuntimeException("License Server installation error 0000000F2", ex);
        }
    }

    static {
        provider = new BouncyCastleProvider();
    }
}
